<template>
  <div
    class="container_box"
    id="video_box"
  >

    <van-icon
      size="26"
      name="search"
      class="search"
      @click="$router.push('/search')"
    />
    <div class="van_swipe">
      <!--vant van-swipe 滑动组件 -->
      <van-swipe
        @change="onChange"
        vertical
        :loop="false"
        :initial-swipe=currentIndex
        :show-indicators="false"
      >
        <van-swipe-item
          v-for="(item, index) in videoList"
          :key="index"
          class="product_swiper"
        >
          <div
            class="video_container"
            @click="pauseVideo(index)"
          >
            <video
              @touchend="isMoveToPerson(item.userid,$event)"
              @touchstart="touchstart"
              :class="[isAndroid&&(!isWeiXin)?(isShrink?'video_box3':'video_box'):'video_box2','video_base'] "
              webkit-playsinline="true"
              x5-playsinline=""
              x5-video-player-type="h5"
              x5-video-player-fullscreen=""
              playsinline
              preload="auto"
              :poster="item.baseUrl+item.poster"
              :src="item.baseUrl+item.src"
              :playOrPause="playOrPause"
              x-webkit-airplay="allow"
              x5-video-orientation="portrait"
              @ended="onPlayerEnded($event)"
              loop="loop"
              :ref="`video${index}`"
            ></video>
            <!-- 封面 -->

            <!-- 播放暂停按钮 -->
            <div
              v-show="iconPlayShow"
              class="icon_play"
            >

            </div>
          </div>
          <!-- 右侧点赞、分享功能 -->
          <div class="tools_right">
            <div
              class="shrinkVideo tools_r_li"
              v-show="isAndroid&&!isWeiXin"
            >
              <van-icon
                name="shrink"
                size="40px"
                @click="isShrink = !isShrink"
              />
            </div>
            <div
              class="avatar-title-wrap tools_r_li"
              @click=" $router.push({name: 'user',params: {userid: item.userid }})"
            >
              <van-image
                class="avatar"
                round
                fit="cover"
                :src="item.baseUrl+item.photo"
              />
              <span
                class="addFollow"
                v-show="!item.isFollow"
                @click.stop="followUser(item.userid)"
              >+</span>

            </div>
            <div
              class="tools_r_li"
              @click="changeFollow(item, index)"
            >
              <div class="li_wrap">
                <div class="tools_r_num">
                  <van-icon
                    name="like"
                    size="40px"
                    :ref="`love${index}`"
                    @click="inToMyLove(index,item._id)"
                    :color="item.isLike?'#f95075':'#ffffff'"
                    :class="item.isLike?'follow_active':''"
                  />
                  <div class="tools_r_num">{{ item.likeNum }}</div>
                </div>
              </div>
            </div>
            <div
              class="tools_r_li"
              @click="changeShare"
            >
              <div class="li_wrap">
                <van-icon
                  name="chat"
                  size='40px'
                  @click="onCommentShow"
                />
                <div class="tools_r_num">{{ item.comments.length }}</div>
              </div>
            </div>
            <div
              class="tools_r_li"
              @click="isShareShow = true"
            >
              <van-icon
                name="share"
                size="40px"
              />
            </div>
          </div>
          <!-- 底部作品描述 -->
          <div class="production_box">
            <div
              class="position"
              @click="$router.push({name:'map',params:{key:item.position}})"
            >
              <van-icon
                name="location"
                color="green"
              />{{item.position}}
            </div>
            <div class="production_name">
              <span
                class="videoAuthor"
                @click=" $router.push({name: 'user',params: {userid: item.userid }})"
              >
                @{{ item.name }}
              </span>
              <span class="time"> ·{{item.publictime}} </span>
            </div>
            <div class="production_des">
              {{item.introduce}} <span
                @click="$router.push(`/search?key=${label}`)"
                style="color:#aaa;"
                v-for="label in item.choosenVideoLabel"
                :key="label"
              > &nbsp;#{{label}}</span>
            </div>

          </div>
        </van-swipe-item>
      </van-swipe>
      <!--底部操作栏-->
      <van-popup
        @closed="onCommentClose"
        v-model="isCommentShow"
        position="bottom"
        get-container="body"
        :style="{ height: '50%' }"
      >
        <comment-list
          @listenReplyRecomment="listenReplyRecomment"
          :videoid="videoid"
        ></comment-list>
        <div
          class="commentVideo"
          @click="cancelReply"
          v-show="replyTpye"
        >回复视频</div>
        <van-field
          v-model="inputComment"
          class="inputComment"
          rows="1"
          autosize
          type="textarea"
          :placeholder="placeholder"
          show-word-limit
          ref="inputComment"
          id="inputComment"
        >
          <template #button>
            <span>
              <van-icon
                name="arrow-up"
                class="onConfirmComment"
                size="25px"
                @click="onConfirmComment"
              />
            </span>
          </template>
        </van-field>
      </van-popup>
      <van-popup
        v-model="isShareShow"
        position="bottom"
        get-container="body"
        :style="{ height: '20%' }"
      >
        <ul class="shareItem">
          <li
            v-clipboard:copy="baseURL+'/#/user/' + this.userid + '/2/'+ videoList[this.current]._id"
            v-clipboard:success="onCopyLink"
          >
            <van-icon
              name="wechat"
              color="#2ddd71"
            />
            <div>微信</div>
          </li>
          <li
            v-clipboard:copy="baseURL+'/#/user/' + this.userid + '/2/'+ videoList[this.current]._id"
            v-clipboard:success="onCopyLink"
            @click="shareToFriend"
          >
            <van-icon name="friends" />
            <div>好友</div>
          </li>
          <li @click="downVideo(videoList[current])">
            <van-icon name="down" />
            <div>下载</div>
          </li>
          <li
            v-clipboard:copy="baseURL+'/#/user/' + this.userid + '/2/'+ videoList[this.current]._id"
            v-clipboard:success="onCopyLink"
          >
            <van-icon name="share" />
            <div>链接</div>
            <div
              id="biao1"
              ref="copyText"
              style="display:none"
            >{{videoList[this.current].baseUrl+videoList[this.current].src}}</div>
          </li>
        </ul>
      </van-popup>
    </div>
  </div>
</template>
<script>
import commentList from '@/components/comment-list'
import globalBus from '@/utils/global-bus'
import { handleDownLoad } from '@/api/video'

import { addUserLikeVideo, removeUserLikeVideo, createComment, addUserFollow, getUserFocusVideo } from '@/api/user'

export default {
  name: 'videoChild',
  components: {
    commentList
  },
  data () {
    const u = navigator.userAgent
    return {
      current: 0,
      active: 1,
      videoList: [{ comments: [], baseUrl: '' }],
      isVideoShow: true,
      playOrPause: true,
      video: null,
      iconPlayShow: true,
      isAndroid: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1,
      isiOS: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
      tabIndex: 0,
      showShareBox: false,
      loveCount: 0,
      x: 1,
      isCommentShow: false,
      currentIndex: 0,
      inputComment: '',
      currentVideoCommentList: [],
      currentCommentPage: 0,
      placeholder: '请输入评论',
      replyTpye: 0,
      replyCommentid: {},
      currentVideoPage: 0,
      isShareShow: false,
      isShrink: false
    }
  },
  created () {
    this.getUserFocusVideo()
    globalBus.$on('follow-update', (value) => {
      this.videoList[this.current].isFollow = value
    })
  },
  computed: {
    baseURL () {
      return 'http://' + location.host
    },
    videoid () {
      return this.videoList[this.current]._id
    },
    isWeiXin () {
      var ua = window.navigator.userAgent.toLowerCase()
      var isWeixin = ua.indexOf('micromessenger') !== -1
      if (isWeixin) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    async getUserFocusVideo () {
      try {
        const res = await getUserFocusVideo(++this.currentVideoPage)
        const videoList = res.data.data
        this.videoList = videoList
        var index = this.videoList.findIndex(v => v._id === this.videoid)
        this.currentIndex = index
        this.current = index
        if (index === this.videoList.length - 1) {
          const res2 = await getUserFocusVideo(++this.currentVideoPage)
          const myvideos = res2.data.data
          this.videoList.push(...myvideos)
          this.currentIndex = this.current
        }
      } catch (error) {
        this.$store.commit('setUser', null)
        return this.$router.push('/login')
      }
    },
    changeFollow (item, index) {
      this.videoList[index].follow = !this.videoList[index].follow
    },
    changeShare () {
      this.showShareBox = true
    },

    async onChange (index) {
      if (this.iconPlayShow) {
        this.iconPlayShow = false
      }
      const beforeVideo = this.$refs[`video${this.current}`][0]
      beforeVideo.pause()
      const CurrentVideo = this.$refs[`video${index}`][0]
      CurrentVideo.play()
      this.current = index
      this.currentVideoCommentList = []
      if (index === this.videoList.length - 1) {
        const res2 = await getUserFocusVideo(++this.currentVideoPage)
        const myvideos = res2.data.data
        this.videoList.push(...myvideos)
        this.currentIndex = this.current
      }
      this.replyTpye = 0
      this.placeholder = '请输入评论'
    },
    pauseVideo (index) {
      const CurrentVideo = this.$refs[`video${index}`][0]
      if (this.iconPlayShow === true) {
        CurrentVideo.play()
        this.iconPlayShow = false
      } else {
        CurrentVideo.pause()
        this.iconPlayShow = true
      }
    },
    playvideo () {
      const video = document.querySelectorAll('video')[this.current]
      this.isVideoShow = false
      this.iconPlayShow = false
      video.play()
      window.onresize = function () {
        video.style.width = window.innerWidth + 'px'
        video.style.height = window.innerHeight + 'px'
      }
    },

    onPlayerEnded () {
      this.isVideoShow = true
      this.current += this.current
    },
    touchstart (event) {
      this.x = event.touches[0].clientX
    },
    isMoveToPerson (userid, event) {
      var endx = event.changedTouches[0].clientX
      if (this.x - endx > 150) {
        this.$router.push({
          name: 'user',
          params: {
            userid:
              userid
          }
        })
      }
    },
    async inToMyLove (index, videoid) {
      try {
        if (!this.videoList[index].isLike) {
          const res = await addUserLikeVideo(this.$store.state.user.userid, videoid)
          if (res.data.meta.status === 200) {
            this.videoList[index].likeNum++
            this.videoList[index].isLike = true
          }
        } else {
          const res = await removeUserLikeVideo(this.$store.state.user.userid, videoid)
          if (res.data.meta.status === 200) {
            this.videoList[index].likeNum--
            this.videoList[index].isLike = false
          }
        }
      } catch (error) {
      }
    },
    async onConfirmComment () {
      if (!this.$store.state.user) { return this.$toast('未登录,请先登录账号') }
      if (!this.inputComment || this.inputComment === '') { return this.$toast('不能发布空消息') }

      try {
        this.$toast.loading({
          duration: 0, // 持续时间，0表示持续展示不停止
          forbidClick: true, // 是否禁止背景点击
          message: '发表中...' // 提示消息
        })
        // 如果为1,则为回复
        var res
        if (this.replyTpye) {
          if (this.replyTpye === 2) {
            res = await createComment(this.$store.state.user.userid, {
              commentid: this.replyCommentid._id,
              content: this.placeholder + this.inputComment
            })
          } else {
            res = await createComment(this.$store.state.user.userid, {
              commentid: this.replyCommentid._id,
              content: this.inputComment
            })
          }
        } else {
          res = await createComment(this.$store.state.user.userid, {
            videoid: this.videoList[this.current]._id,
            content: this.inputComment
          })
        }
        globalBus.$emit('updataComment', res.data.data)
        this.inputComment = ''
        this.videoList[this.current].comments.push('.')
        this.$toast.success('发表成功')
      } catch (error) {
      }
    },
    onCommentShow () {
      this.isCommentShow = true
      globalBus.$emit('onLoadComment')
    },
    backPage () {
      this.currentVideoCommentList = []
      this.$router.back()
    },
    onCommentClose () {
      globalBus.$emit('clearComment')
    },
    listenReplyRecomment (commentid, name, type) {
      if (type === 1) {
        this.placeholder = `回复${name}:`
        this.$refs.inputComment.focus()
        this.replyTpye = 2
        this.replyCommentid._id = commentid
      } else {
        this.placeholder = `回复${name}:`
        this.$refs.inputComment.focus()
        this.replyTpye = 1
        this.replyCommentid._id = commentid
      }
    },
    cancelReply () {
      this.replyTpye = 0
      this.placeholder = '请输入评论'
    },
    async followUser (userid) {
      if (!this.$store.state.user) { return this.$toast('未登录,请先登录账号') }
      try {
        await addUserFollow(this.$store.state.user.userid, { userid: userid })
        this.videoList[this.current].isFollow = true
        this.$toast('关注了用户')
      } catch (error) {
      }
    },
    download (blobUrl, name) {
      const a = document.createElement('a')
      a.download = name
      a.href = blobUrl
      a.click()
    },
    onCopyLink () {
      this.$toast('视频地址复制成功,赶紧去分享把！')
    },
    downVideo (item) {
      if (window.localStorage.getItem('user') === 'null') {
        return this.$toast('请先登录再操作')
      }
      const url = item.src
      const name = item.introduce + '.mp4'
      handleDownLoad(url, name).then(res => {
        this.$toast('正在下载视频。。。')
        const blob = new Blob([res.data])
        const blobUrl = window.URL.createObjectURL(blob)
        this.download(blobUrl, name)
      })
    },
    shareToFriend () {
      this.$router.push('message')
    }
  }
}
</script>
<style scoped lang='less'>
.time {
  color: #8e8f95;
}
.video-player,
.van_swipe,
.van-swipe,
.video_container {
  height: 100%;
  width: 100%;
}
.container_box {
  width: 100%;
  height: 660px;
}
.video_base {
  object-fit: cover !important;
  max-height: 100%;
  z-index: 999;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  overflow: hidden;
}
.video_box2 {
  width: 100%;
}

.video_box3 {
  width: 25%;
}

.video_box {
  width: 84%;
}
video {
  object-position: 0 0;
}
.icon_play {
  height: 0;
  width: 0;
  border-left: 100px solid;
  border-radius: 15px;
  border: 55px solid;
  position: absolute;
  top: 45%;
  right: 0;
  left: 60px;
  bottom: auto;
  margin: auto;
  z-index: 999;
  border-color: transparent transparent transparent #e7eaed;
  opacity: 0.5;
}
.play,
.platStart {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 100%;
}
/* 点赞，转发 */
.tools_right {
  z-index: 999999;
  position: absolute;
  right: 4px;
  bottom: 130px;
}
.tools_r_li {
  margin-bottom: 20px;
  color: #fff;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.tools_r_li:last-child {
  margin-bottom: 0px;
}
.icon_right {
  margin-bottom: 5px;
  font-size: 42px;
  display: block;
  text-shadow: 0px 0px 10px #9d9d9d;
  /*transition: .5s;*/
}
.production_box {
  z-index: 1001;
  position: absolute;
  /* right: 16px; */
  bottom: 30px;
  text-align: left;
  padding: 0 15px 15px 15px;
  color: #fff;
  width: 100%;
  left: 0;
  box-sizing: border-box;
}
.production_name {
  font-size: 18px;
  margin-bottom: 10px;
  color: #fff;
}
.production_des {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  min-height: 15px;
  font-style: normal;
  color: #eee;
  font-size: 16px;
}
.position {
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  min-height: 15px;
  font-style: normal;
  color: #eee;
  font-size: 16px;
}

.production_top {
  display: inline-block;
  padding: 6px;
  margin-bottom: 5px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 6px;
  margin-top: 5px;
}
.product_go {
  color: #fbdd21;
}
.production_title {
  margin-left: 4px;
}
.bottom_tab {
  margin-bottom: 50px;
  width: 50%;
  text-align: center;
  float: left;
  color: #c9c9c9;
  padding: 10px 0;
}
.bottom_tab_span {
  line-height: 30px;
  border-bottom: 2px solid transparent;
  font-weight: 600;
  font-size: 16px;
  display: inline-block;
  /* padding: 0 4px; */
  transition: 0.5s all;
}
.tab_active .bottom_tab_span {
  border-bottom: 2px solid #fda085;
  color: #fda085;
}
.icon-shoucang {
  transition: 0.5s all;
}
.follow_active {
  color: #fda085;
  animation: showHeart 0.5s ease-in-out 0s;
}
@keyframes showHeart {
  0% {
    color: #f44;
    transform: scale(1);
  }
  25% {
    color: #fff;
    transform: scale(0);
  }
  80% {
    color: #f44;
    transform: scale(1.2);
  }
  100% {
    color: #f44;
    transform: scale(1);
  }
}

.pengyouquan {
  color: #47d000;
}
.pengyouquan_li {
  animation: rotating 8s linear infinite;
}
@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}
.weixin {
  color: #20ca2e;
}
.lianjie {
  color: #cdcdcd;
}
.share_active {
  bottom: 0px;
}
.avatar-title-wrap {
  display: flex;
  align-items: center;
  .avatar {
    width: 50px;
    height: 50px;
    padding: 2px;
    background: #fff;
  }
  .addFollow {
    padding-left: 3px;
    z-index: 11111;
    background-color: #f73057;
    position: absolute;
    left: 17px;
    top: 40px;
    width: 18px;
    height: 18px;
    color: #fff;
    border-radius: 15px;
    font-size: 18px;
    z-index: 11111;
  }
}
.navigatorTab {
  z-index: 1111;
  position: fixed;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}
/deep/.van-tabs__nav {
  background-color: rgba(25, 25, 35, 0) !important;
}
.tools_r_num {
  text-align: center;
}
.search {
  z-index: 10000;
  position: fixed;
  right: 10px;
  top: 10px;
}
.return {
  z-index: 11111;
  position: fixed;
  top: 14px;
  left: 10px;
}
.commentVideo {
  position: fixed;
  bottom: 50px;
  color: #555;
  background-color: rgba(161, 161, 161, "0.9");
  font-size: 20px;
  right: 10px;
}
.inputComment {
  position: fixed;
  bottom: 50px;
}
.onConfirmComment {
  background: #f95075;
  position: fixed;
  bottom: 60px;
  right: 10px;
  border-radius: 25px;
  color: #fff;
}
.van-cell {
  background: #fff !important;
}
.shareItem {
  padding-top: 10px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: nowrap;

  li {
    padding-left: 20px;
    font-size: 40px;
  }
  li div {
    color: #666;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 17px;
  }
}
</style>
